//阚子路
#include "DataManager.h"
#include <QDebug>
#include <QFile>
#include <QIODevice>
#include <QTextStream>

DataManager::DataManager(QObject* parent) : QObject(parent) {}

// 原有：模拟导入“普通组件参数”（如光伏、储能）
void DataManager::importCsvData(const QString& path) {
    qDebug() << "模拟导入普通组件 CSV：" << path;
    QList<ComponentParam> mockParams;
    // （可选）这里可添加普通组件的模拟参数
    emit dataImported(mockParams);
}

// 导入CSV，通过表头判断是否为柴油发电机时间-功率数据
void DataManager::importDieselGenCsv(const QString& path) {
    qDebug() << "开始导入柴油发电机CSV：" << path;

    // 1. 打开文件
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QString error = "文件打开失败：" + path;
        qDebug() << error;
        emit importFailed(error);
        return;
    }

    // 2. 读取表头并识别
    QTextStream in(&file);
    QString header = in.readLine().trimmed(); // 去除首尾空格
    const QString targetHeader = "time_step,power_kW"; // 目标表头

    if (header != targetHeader) {
        // 表头不匹配，直接判定为非目标文件
        QString error = "表头不匹配（需为：" + targetHeader + "）";
        qDebug() << error;
        file.close();
        emit importFailed(error);
        return;
    }

    // 3. 解析数据（时间步→功率）
    QMap<int, float> dieselTimePower;
    int lineNum = 1; // 记录行号（从1开始，跳过表头）

    while (!in.atEnd()) {
        lineNum++;
        QString line = in.readLine().trimmed();
        if (line.isEmpty()) continue; // 跳过空行

        // 按逗号拆分字段
        QStringList fields = line.split(",");
        if (fields.size() != 2) {
            qDebug() << "第" << lineNum << "行格式错误（需2个字段），跳过";
            continue;
        }

        // 转换时间步（int）和功率（float）
        bool timeOk = false, powerOk = false;
        int timeStep = fields[0].toInt(&timeOk);
        float power = fields[1].toFloat(&powerOk);

        if (!timeOk || !powerOk) {
            qDebug() << "第" << lineNum << "行数据无效（非数字），跳过";
            continue;
        }

        // 存入映射
        dieselTimePower[timeStep] = power;
        qDebug() << "解析成功：第" << lineNum << "行 → 时间" << timeStep << "，功率" << power;
    }

    // 4. 关闭文件并校验结果
    file.close();

    if (dieselTimePower.isEmpty()) {
        QString error = "CSV无有效数据（或所有行格式错误）";
        qDebug() << error;
        emit importFailed(error);
    } else {
        qDebug() << "柴油发电机CSV解析完成，共" << dieselTimePower.size() << "个时间点";
        qDebug()<<"importsuccess";
        emit dieselGenTimePowerLoaded(dieselTimePower);

    }
}

void DataManager::importPvCsv(const QString& path) {
    qDebug() << "开始导入光伏CSV：" << path;

    QFile file(path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "光伏文件打开失败：" << path;
        emit importFailed("光伏文件打开失败");
        return;
    }

    QTextStream in(&file);
    QString header = in.readLine().trimmed();
    const QString targetHeader = "time_step,power_kW"; // 光伏CSV的表头

    if (header != targetHeader) {
        qDebug() << "光伏CSV表头不匹配，需为：" << targetHeader;
        file.close();
        emit importFailed("光伏CSV表头不匹配");
        return;
    }

    QMap<int, float> pvTimePower;
    int lineNum = 1;
    while (!in.atEnd()) {
        lineNum++;
        QString line = in.readLine().trimmed();
        if (line.isEmpty()) continue;

        QStringList fields = line.split(",");
        if (fields.size() != 2) {
            qDebug() << "光伏CSV第" << lineNum << "行格式错误，跳过";
            continue;
        }

        bool timeOk = false, powerOk = false;
        int timeStep = fields[0].toInt(&timeOk);
        float power = fields[1].toFloat(&powerOk);

        if (timeOk && powerOk) {
            pvTimePower[timeStep] = power;
            qDebug() << "解析光伏数据：时间" << timeStep << "→ 功率" << power;
        } else {
            qDebug() << "光伏CSV第" << lineNum << "行数据无效，跳过";
        }
    }

    file.close();

    if (pvTimePower.isEmpty()) {
        emit importFailed("光伏CSV无有效数据");
    } else {
        emit pvDataLoaded(pvTimePower); // 发射光伏数据信号
    }
}

// 导入储能CSV数据
void DataManager::importEnergyStorageCsv(const QString& path) {
    qDebug() << "开始导入储能CSV：" << path;

    QFile file(path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "储能文件打开失败：" << path;
        emit importFailed("储能文件打开失败");
        return;
    }

    QTextStream in(&file);
    QString header = in.readLine().trimmed();
    const QString targetHeader = "time_step,power_kW"; // 储能CSV表头

    if (header != targetHeader) {
        qDebug() << "储能CSV表头不匹配，需为：" << targetHeader;
        file.close();
        emit importFailed("储能CSV表头不匹配");
        return;
    }

    QMap<int, float> esTimePower;
    int lineNum = 1;
    while (!in.atEnd()) {
        lineNum++;
        QString line = in.readLine().trimmed();
        if (line.isEmpty()) continue;

        QStringList fields = line.split(",");
        if (fields.size() != 2) {
            qDebug() << "储能CSV第" << lineNum << "行格式错误，跳过";
            continue;
        }

        bool timeOk = false, powerOk = false;
        int timeStep = fields[0].toInt(&timeOk);
        float power = fields[1].toFloat(&powerOk);

        if (timeOk && powerOk) {
            esTimePower[timeStep] = power;
            qDebug() << "解析储能数据：时间" << timeStep << "→ 功率" << power;
        } else {
            qDebug() << "储能CSV第" << lineNum << "行数据无效，跳过";
        }
    }

    file.close();

    if (esTimePower.isEmpty()) {
        emit importFailed("储能CSV无有效数据");
    } else {
        emit energyStorageDataLoaded(esTimePower); // 发射储能数据信号
    }
}

// 导入负载CSV数据
void DataManager::importLoadCsv(const QString& path) {
    qDebug() << "开始导入负载CSV：" << path;

    QFile file(path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "负载文件打开失败：" << path;
        emit importFailed("负载文件打开失败");
        return;
    }

    QTextStream in(&file);
    QString header = in.readLine().trimmed();
    const QString targetHeader = "time_step,power_kW"; // 负载CSV表头

    if (header != targetHeader) {
        qDebug() << "负载CSV表头不匹配，需为：" << targetHeader;
        file.close();
        emit importFailed("负载CSV表头不匹配");
        return;
    }

    QMap<int, float> loadTimePower;
    int lineNum = 1;
    while (!in.atEnd()) {
        lineNum++;
        QString line = in.readLine().trimmed();
        if (line.isEmpty()) continue;

        QStringList fields = line.split(",");
        if (fields.size() != 2) {
            qDebug() << "负载CSV第" << lineNum << "行格式错误，跳过";
            continue;
        }

        bool timeOk = false, powerOk = false;
        int timeStep = fields[0].toInt(&timeOk);
        float power = fields[1].toFloat(&powerOk);

        if (timeOk && powerOk) {
            loadTimePower[timeStep] = power;
            qDebug() << "解析负载数据：时间" << timeStep << "→ 功率" << power;
        } else {
            qDebug() << "负载CSV第" << lineNum << "行数据无效，跳过";
        }
    }

    file.close();

    if (loadTimePower.isEmpty()) {
        emit importFailed("负载CSV无有效数据");
    } else {
        emit loadDataLoaded(loadTimePower); // 发射负载数据信号
    }
}

// 导入电网CSV数据
void DataManager::importGridCsv(const QString& path) {
    qDebug() << "开始导入电网CSV：" << path;

    QFile file(path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "电网文件打开失败：" << path;
        emit importFailed("电网文件打开失败");
        return;
    }

    QTextStream in(&file);
    QString header = in.readLine().trimmed();
    const QString targetHeader = "time_step,power_kW"; // 电网CSV表头

    if (header != targetHeader) {
        qDebug() << "电网CSV表头不匹配，需为：" << targetHeader;
        file.close();
        emit importFailed("电网CSV表头不匹配");
        return;
    }

    QMap<int, float> gridTimePower;
    int lineNum = 1;
    while (!in.atEnd()) {
        lineNum++;
        QString line = in.readLine().trimmed();
        if (line.isEmpty()) continue;

        QStringList fields = line.split(",");
        if (fields.size() != 2) {
            qDebug() << "电网CSV第" << lineNum << "行格式错误，跳过";
            continue;
        }

        bool timeOk = false, powerOk = false;
        int timeStep = fields[0].toInt(&timeOk);
        float power = fields[1].toFloat(&powerOk);

        if (timeOk && powerOk) {
            gridTimePower[timeStep] = power;
            qDebug() << "解析电网数据：时间" << timeStep << "→ 功率" << power;
        } else {
            qDebug() << "电网CSV第" << lineNum << "行数据无效，跳过";
        }
    }

    file.close();

    if (gridTimePower.isEmpty()) {
        emit importFailed("电网CSV无有效数据");
    } else {
        emit gridDataLoaded(gridTimePower); // 发射电网数据信号
    }
}

void DataManager::importGPriceCsv(const QString& path) {
    qDebug() << "开始导入电价CSV：" << path;

    QFile file(path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "电价文件打开失败：" << path;
        emit importFailed("电价文件打开失败");
        return;
    }

    QTextStream in(&file);
    QString header = in.readLine().trimmed();
    const QString targetHeader = "time_step,price"; // 电价CSV表头（时间步, 电价）

    if (header != targetHeader) {
        qDebug() << "电价CSV表头不匹配，需为：" << targetHeader;
        file.close();
        emit importFailed("电价CSV表头不匹配");
        return;
    }

    QMap<int, float> gPriceTimePrice;
    int lineNum = 1;
    while (!in.atEnd()) {
        lineNum++;
        QString line = in.readLine().trimmed();
        if (line.isEmpty()) continue;

        QStringList fields = line.split(",");
        if (fields.size() != 2) {
            qDebug() << "电价CSV第" << lineNum << "行格式错误，跳过";
            continue;
        }

        bool timeOk = false, priceOk = false;
        int timeStep = fields[0].toInt(&timeOk);
        float price = fields[1].toFloat(&priceOk);

        if (timeOk && priceOk) {
            gPriceTimePrice[timeStep] = price;
            qDebug() << "解析电价数据：时间" << timeStep << "→ 电价" << price;
        } else {
            qDebug() << "电价CSV第" << lineNum << "行数据无效，跳过";
        }
    }

    file.close();

    if (gPriceTimePrice.isEmpty()) {
        emit importFailed("电价CSV无有效数据");
    } else {
        emit gPriceDataLoaded(gPriceTimePrice); // 发射电价数据信号
    }
}

// --------------------- 以下为新增的导出方法 ---------------------

void DataManager::exportDieselGenCsv(const QString& savePath, const QMap<int, float>& dieselTimePower) {
    // 1. 检查映射表是否有数据
    if (dieselTimePower.isEmpty()) {
        QString error = "无柴油发电机数据可导出（未导入过CSV或数据为空）";
        qDebug() << error;
        emit exportFailed(error);
        return;
    }

    // 2. 打开文件（写入+覆盖模式）
    QFile file(savePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
        QString error = "文件保存失败：" + savePath + "（可能无权限或文件被占用）";
        qDebug() << error;
        emit exportFailed(error);
        return;
    }

    // 3. 写入CSV（表头+数据）
    QTextStream out(&file);
    out << "time_step,power_kW\n"; // 与导入表头一致
    for (auto it = dieselTimePower.begin(); it != dieselTimePower.end(); ++it) {
        out << it.key() << "," << it.value() << "\n";
    }

    // 4. 关闭文件+日志提示
    file.close();
    qDebug() << "柴油发电机数据导出成功：" << savePath;
}

void DataManager::exportPvCsv(const QString& savePath, const QMap<int, float>& pvTimePower) {
    if (pvTimePower.isEmpty()) {
        QString error = "无光伏数据可导出（未导入过CSV或数据为空）";
        qDebug() << error;
        emit exportFailed(error);
        return;
    }

    QFile file(savePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
        QString error = "光伏数据文件保存失败：" + savePath;
        qDebug() << error;
        emit exportFailed(error);
        return;
    }

    QTextStream out(&file);
    out << "time_step,power_kW\n";
    for (auto it = pvTimePower.begin(); it != pvTimePower.end(); ++it) {
        out << it.key() << "," << it.value() << "\n";
    }

    file.close();
    qDebug() << "光伏数据导出成功：" << savePath;
}

void DataManager::exportEnergyStorageCsv(const QString& savePath, const QMap<int, float>& esTimePower) {
    if (esTimePower.isEmpty()) {
        QString error = "无储能数据可导出（未导入过CSV或数据为空）";
        qDebug() << error;
        emit exportFailed(error);
        return;
    }

    QFile file(savePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
        QString error = "储能数据文件保存失败：" + savePath;
        qDebug() << error;
        emit exportFailed(error);
        return;
    }

    QTextStream out(&file);
    out << "time_step,power_kW\n";
    for (auto it = esTimePower.begin(); it != esTimePower.end(); ++it) {
        out << it.key() << "," << it.value() << "\n";
    }

    file.close();
    qDebug() << "储能数据导出成功：" << savePath;
}

void DataManager::exportLoadCsv(const QString& savePath, const QMap<int, float>& loadTimePower) {
    if (loadTimePower.isEmpty()) {
        QString error = "无负载数据可导出（未导入过CSV或数据为空）";
        qDebug() << error;
        emit exportFailed(error);
        return;
    }

    QFile file(savePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
        QString error = "负载数据文件保存失败：" + savePath;
        qDebug() << error;
        emit exportFailed(error);
        return;
    }

    QTextStream out(&file);
    out << "time_step,power_kW\n";
    for (auto it = loadTimePower.begin(); it != loadTimePower.end(); ++it) {
        out << it.key() << "," << it.value() << "\n";
    }

    file.close();
    qDebug() << "负载数据导出成功：" << savePath;
}

void DataManager::exportGridCsv(const QString& savePath, const QMap<int, float>& gridTimePower) {
    if (gridTimePower.isEmpty()) {
        QString error = "无电网数据可导出（未导入过CSV或数据为空）";
        qDebug() << error;
        emit exportFailed(error);
        return;
    }

    QFile file(savePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
        QString error = "电网数据文件保存失败：" + savePath;
        qDebug() << error;
        emit exportFailed(error);
        return;
    }

    QTextStream out(&file);
    out << "time_step,power_kW\n";
    for (auto it = gridTimePower.begin(); it != gridTimePower.end(); ++it) {
        out << it.key() << "," << it.value() << "\n";
    }

    file.close();
    qDebug() << "电网数据导出成功：" << savePath;
}

void DataManager::exportGPriceCsv(const QString& savePath, const QMap<int, float>& gPriceTimePrice) {
    if (gPriceTimePrice.isEmpty()) {
        QString error = "无电价数据可导出（未导入过CSV或数据为空）";
        qDebug() << error;
        emit exportFailed(error);
        return;
    }

    QFile file(savePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
        QString error = "电价数据文件保存失败：" + savePath;
        qDebug() << error;
        emit exportFailed(error);
        return;
    }

    QTextStream out(&file);
    out << "time_step,price\n"; // 与电价导入表头一致
    for (auto it = gPriceTimePrice.begin(); it != gPriceTimePrice.end(); ++it) {
        out << it.key() << "," << it.value() << "\n";
    }

    file.close();
    qDebug() << "电价数据导出成功：" << savePath;
}
